package com.lbyl.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.content.ContentValues.TAG;

/**
 * 网络请求工具类,用get方式访问,指定的网址.返回response或null
 *
 * @author libin996@outlook.com
 */

public class ConNetUtil {
    /**
     * 用get方式访问,指定的网址.返回response
     * @param urlStr
     * @return 完整的response
     */
    public static String httpGetAndRes(String urlStr){
        String response;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() != 200) {
                System.out.println("服务器拒绝访问,状态码是"+connection.getResponseCode());
                return null;
            }
            InputStream ins = connection.getInputStream();

            BufferedReader bfReader = new BufferedReader(new InputStreamReader(ins));
            String tmpRes ;
            StringBuffer stringBuffer = new StringBuffer();
            while ((tmpRes = bfReader.readLine()) != null) {
                stringBuffer.append(tmpRes);
            }
            ins.close();
            response = stringBuffer.toString();


        } catch (Exception e) {
            response = "connect_error";
            e.printStackTrace();
            Log.i(TAG, "httpGetAndRes: 网络连接失败.检查NetUtil");
        }

        return response;
    }
}
